
<div align="center">
<?php
function show_cat(){
echo '<ul >';
$sql_all="SELECT * FROM danhmuc";
$sql=mysql_query($sql_all) or die (mysql_error()); // lay tat ca danh muc
    if(mysql_num_rows($sql) > 0) {
        while($r=mysql_fetch_array($sql)) {
            if($r['parent_id'] == 0) { // tim danh muc cha
                if(isset($_GET['dm']))  // doi style cua danh muc cha sau khi da click vao
                {
                    $iddm=intval($_GET['dm']); // lay danh muc hien tai
                    if($iddm == $r['id']) // so sanh voi danh muc trong data, neu = thay style khac
                    {
                        echo "{$r['tendm']}";                        
                    }else {
                         echo "{$r['tendm']}";         
                    }
                }else // show tat ca danh muc cha
                {
                    echo "{$r['tendm']}";   
                }
                
                
                }
            }
            if(isset($_GET['dm'])) {                 
                // query lay danh muc con
                $sql1=mysql_query("SELECT * FROM danhmuc WHERE parent_id = '$iddm' ORDER BY id ASC") or die (mysql_error());
                $num=mysql_num_rows($sql1);
                if($num >0){
                echo "<li><span>";
                    while($r1=mysql_fetch_array($sql1)){
                        echo "{$r1['tendm']} |";
                        
                    }
                echo "</span></li>";    
                
                }
                else {// luon hien thi danh muc con moi khi an vao 1 danh muc cha.

                $sel_query="select ch.tendm as ten_cha,c.id as id_con, c.tendm as ten_con from danhmuc as c inner join danhmuc as ch on c.parent_id = ch.id where c.parent_id = (select d.id
                from danhmuc as d inner join danhmuc as dm on d.id = dm.parent_id where dm.id=$iddm);";
                         
                    $sql2=mysql_query($sel_query) or die (mysql_error());
                    
                    
                    if(mysql_num_rows($sql2) > 0) {
                        
                        echo "<li><span>";
                    while($r2=mysql_fetch_array($sql2))
                    {
                           
                           if($r2['id_con'] == $iddm){
                            echo "{$r2['ten_con']}<|";
                            }else {
                                echo "{$r2['ten_con']} |";
                            }
                              
                    } 
                }
                }
            }
            
        }
echo '</ul>';

}
show_cat();

?>

</div>
